package com.cycplus.test.ui

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

class GridLastRowMarginDecoration(private val spanCount: Int, private val lastRowBottomSpacingPx: Int, private val normalBottomSpacingPx: Int = 0) : RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        val position = parent.getChildAdapterPosition(view)
        val itemCount = parent.adapter?.itemCount ?: 0
        // 判断是否在最后一行
        if (isInLastRow(position, itemCount, spanCount)) {
            outRect.bottom = lastRowBottomSpacingPx
        } else {
            outRect.bottom = normalBottomSpacingPx
        }
    }

    private fun isInLastRow(position: Int, itemCount: Int, spanCount: Int): Boolean {
        if (itemCount == 0) return false
        return if (itemCount % spanCount == 0) {
            position > (((itemCount / spanCount) - 1) * spanCount) - 1
        } else {
            position > ((itemCount / spanCount) * spanCount) - 1
        }
    }
}